﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.Pickers;
using Windows.Storage.Streams;
using Windows.UI.Xaml.Media.Imaging;

namespace StudyTime_1.classes
{
   public static class getImg

     

    { 
       
       private static StorageFile storage;
       private static byte[] img;

       private static BitmapImage picture = new BitmapImage();

      async public static Task getImage()
       {
           FileOpenPicker openPicker = new FileOpenPicker();
           openPicker.ViewMode = PickerViewMode.List;
           openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
           openPicker.FileTypeFilter.Add(".jpg");
           openPicker.FileTypeFilter.Add(".jpeg");
           openPicker.FileTypeFilter.Add(".png");
           openPicker.FileTypeFilter.Add(".bmp");
            storage = await openPicker.PickSingleFileAsync();

           if (null != storage)
           {

               var file = await storage.OpenAsync(FileAccessMode.Read);

               Stream inStream = file.AsStreamForRead();

               //BitmapImage tmpImg = new BitmapImage();

               using (MemoryStream br = new MemoryStream())
               {

                   inStream.CopyTo(br);
                   img = br.ToArray();




               }



               var stream = new InMemoryRandomAccessStream();

               using (var writer = new DataWriter(stream))
               {

                   writer.WriteBytes(img);
                   await writer.StoreAsync();
                   writer.DetachStream();


               }
               stream.Seek(0);
               picture.SetSource(stream);

               //insertPreview.Source = tmpImg;

               await stream.FlushAsync();

              


               //errorBox.Text = "Image Loaded.";

           }
           //else
           //{
           //    errorBox.Text = "File was not returned";
           //}
       }

      async public static Task convertToPic(byte [] a)
      {

          img = a;
          var stream = new InMemoryRandomAccessStream();

          using (var writer = new DataWriter(stream))
          {

              writer.WriteBytes(img);
              await writer.StoreAsync();
              writer.DetachStream();


          }
          stream.Seek(0);
          picture.SetSource(stream);

          //insertPreview.Source = tmpImg;

          await stream.FlushAsync();
          
      }

      public static BitmapImage getPicture()
      {
          return picture;
      }

      public static byte[] getArray()
      {
          return img;
      }

    }
}
